﻿
using Basket.API.Data;
using Discount.GRPC;

namespace Basket.API.Baskets.StoreBasket
{
    public record StoreBasketResult(string UserName);
    public record StoreBasketCommand(ShoppingCart ShoppingCart) :ICommand<StoreBasketResult>;

    public class StoreBasketCommandValidator : AbstractValidator<StoreBasketCommand>
    {
        public StoreBasketCommandValidator()
        {
            RuleFor(x => x.ShoppingCart).NotNull().WithMessage("Shopping cart cannot be null");
            RuleFor(x => x.ShoppingCart.UserName).NotEmpty().WithMessage("UserName cannot be empty");
        }
    }

    public class StoreBasketCommandHandler(IBasketRepository basketRepository,
        DiscountProtoService.DiscountProtoServiceClient discountProtoService ) //添加grpc服务后，即可注入
        : ICommandHandler<StoreBasketCommand, StoreBasketResult>
    {
        public async Task<StoreBasketResult> Handle(StoreBasketCommand request, CancellationToken cancellationToken)
        {
            await DeductDiscount(request.ShoppingCart, cancellationToken);

            await basketRepository.UpdateBasketAsync(request.ShoppingCart, cancellationToken);

            return await Task.FromResult(new StoreBasketResult(request.ShoppingCart.UserName));
        }

        private async Task DeductDiscount(ShoppingCart cart, CancellationToken cancellationToken)
        {
            // Communicate with Discount.Grpc and calculate lastest prices of products into sc
            foreach (var item in cart.Items)
            {
                var coupon = await discountProtoService.GetDiscountAsync(new GetDiscountRequest { ProductName = item.ProductName }, cancellationToken: cancellationToken);
                item.Price -= coupon.Amount;
            }
        }
    }

   
}
